from rest_framework import serializers
from rest_framework.serializers import ValidationError
from goods import models



class BrandsSerializer(serializers.ModelSerializer):
    name = serializers.CharField(max_length=32)
    desc = serializers.CharField(min_length=10)
    category = serializers.CharField(write_only=True)
    
    class Meta:
        model = models.GoodsBrands
        fields = ['name', 'logo', 'desc', 'category_name', 'category', 'sorted_num', ]
        extra_kwargs = {
            'category_name': {'read_only': True, },
            'sorted_num': {'write_only': True, 'required': False, 'default': 0},
            'create_time': {'write_only': True, 'required': False, 'default': 0}
        }
        depth = 1
    
    def validate_name(self, data):
        brand = models.GoodsBrands.objects.filter(name=data).first()
        if brand:
            raise ValidationError('品牌已存在！')
        else:
            return data
    
    def validate(self, attrs):
        categorys = eval(attrs.get('category'))  # 得到的是一个列表的字符串 用eval转格式
        category_list = []
        for category in categorys:
            category = models.BrandsCategory.objects.filter(id=category).first()
            category_list.append(category)
        attrs.update({'category': category_list})  # 直接修改 过滤文件md
        return attrs


